﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Einstein.Data;
using Einstein.Utility;
using DevComponents.DotNetBar;
using DevComponents.Editors;
using Einstein.Group.BLL;
using DevComponents.DotNetBar.Controls;
using Einstein.Group.DAL;

namespace Einstein.Platform.Window.Device
{
    public partial class Device_New : Office2007Form
    {
        public string DeviceNO = string.Empty;

        public Device_New()
        {
            InitializeComponent();
        }

       new  private bool Validate()
        {
            if (String.IsNullOrEmpty(DeviceNO))
            {
                if (DeviceInfoBLL.Exist(txtDeviceNO.Text))
                {
                    MyMessageBox.ShowMessage(this, "设备编号有重复，请重新输入");
                    return false;
                }
            }

            if (string.IsNullOrWhiteSpace(ddlDeviceType.Text))
            {
                MyMessageBox.ShowMessage(this, "设备类型必选");

                return false;
            }

            if (string.IsNullOrWhiteSpace(ddlDevicePlace.Text))
            {
                MyMessageBox.ShowMessage(this, "设备位置必选");
                return false;
            }

            if (string.IsNullOrWhiteSpace(ddlDept.Text))
            {
                MyMessageBox.ShowMessage(this, "管理部门必选");
                return false;
            }


            if (string.IsNullOrWhiteSpace(ddlConnectType.Text))
            {
                MyMessageBox.ShowMessage(this, "通讯接口必选");
                return false;
            }

            if (string.IsNullOrWhiteSpace(ddlDeviceType.Text))
            {
                MyMessageBox.ShowMessage(this, "设备类型必选");
                return false;
            }
            int connectTypeID = int.Parse((ddlConnectType.SelectedItem as ComboBoxItem).Name);
            if (connectTypeID == 1)//TCP/IP
            {
                if (string.IsNullOrWhiteSpace(ipaIP.Text))
                {
                    MyMessageBox.ShowMessage(this, "IP地址必填");
                    return false;
                }
                if (string.IsNullOrWhiteSpace(this.ipaDefaultGateway.Text))
                {
                    MyMessageBox.ShowMessage(this, "默认网关必填");
                    return false;
                }
                if (string.IsNullOrWhiteSpace(this.ipaSubMask.Text))
                {
                    MyMessageBox.ShowMessage(this, "子网掩码必填");
                    return false;
                }
            }
            else if (connectTypeID == 2) // 458
            {
                if (string.IsNullOrWhiteSpace(this.integerInput2.Text))
                {
                    MyMessageBox.ShowMessage(this, "端口必填");
                    return false;
                }
            }

            return true;
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            if (!superValidator1.Validate())
                return;

            //validate
            if (!Validate())
                return;


            if (String.IsNullOrEmpty(DeviceNO))
            {
                #region 新增

                var deviceinfo = new DeviceInfo()
                {
                    DeviceNO = txtDeviceNO.Text,
                    DeviceDeptID = 1,
                    DevicePlaceID = int.Parse((ddlDevicePlace.SelectedItem as ComboBoxItem).Name),
                    DeviceTypeID = int.Parse((ddlDeviceType.SelectedItem as ComboBoxItem).Name),
                    ConnectType = int.Parse((ddlConnectType.SelectedItem as ComboBoxItem).Name),
                    IP = ipaIP.Text,
                    DefaultGateway = ipaSubMask.Text,
                    SubnetMask = ipaDefaultGateway.Text,
                    Desc = txtDesc.Text,
                    Port = string.IsNullOrWhiteSpace(integerInput2.Text) ? null : new Nullable<int>(int.Parse(integerInput2.Text)),
                };


                //save
                try
                {
                    if (DeviceInfoBLL.Add(deviceinfo))
                    {
                        //success, close this form
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                catch (Exception ex)
                {
                    MyMessageBox.ShowMessage(this, "保存失败！异常信息：" + ex.Message);
                }

                #endregion
            }
            else
            {
                #region

                var deviceinfo = new DeviceInfo()
                {
                    DeviceNO = DeviceNO,
                    DeviceDeptID = int.Parse((this.ddlDept.SelectedItem as ComboBoxItem).Name),
                    DevicePlaceID = int.Parse((ddlDevicePlace.SelectedItem as ComboBoxItem).Name),
                    DeviceTypeID = int.Parse((ddlDeviceType.SelectedItem as ComboBoxItem).Name),
                    ConnectType = int.Parse((ddlConnectType.SelectedItem as ComboBoxItem).Name),
                    IP = ipaIP.Text,
                    DefaultGateway = ipaSubMask.Text,
                    SubnetMask = ipaDefaultGateway.Text,
                    Desc = txtDesc.Text,
                    Port = string.IsNullOrWhiteSpace(integerInput2.Text) ? null : new Nullable<int>(int.Parse(integerInput2.Text)),
                };


                //save
                try
                {
                    if (DeviceInfoBLL.Update(deviceinfo))
                    {
                        //success, close this form
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                catch (Exception ex)
                {
                    MyMessageBox.ShowMessage(this, "保存失败！异常信息：" + ex.Message);
                }

                #endregion

            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
        }

        private void Device_New_Load(object sender, EventArgs e)
        {
            #region 加载原始数据

            var deviceTypeList = DictionaryBLL.GetByCategory("设备类型");
            ddlDeviceType.Items.Clear();
            foreach (var deviceType in deviceTypeList)
            {
                ddlDeviceType.Items.Add(new ComboBoxItem(deviceType.KeyValue.ToString(), deviceType.KeyName));
            }

            var connectTypeList = DictionaryBLL.GetByCategory("通讯类型");
            ddlConnectType.Items.Clear();
            foreach (var connectType in connectTypeList)
            {
                ddlConnectType.Items.Add(new ComboBoxItem(connectType.KeyValue.ToString(), connectType.KeyName));
            }


            var devicePlaceList = DictionaryBLL.GetByCategory("设备位置");
            ddlDevicePlace.Items.Clear();
            foreach (var devicePlace in devicePlaceList)
            {
                ddlDevicePlace.Items.Add(new ComboBoxItem(devicePlace.KeyValue.ToString(), devicePlace.KeyName));
            }

            var deptList = new DeptInfoDAL().SelectAll();
            ddlDept.Items.Clear();
            foreach (var dept in deptList)
            {
                ddlDept.Items.Add(new ComboBoxItem(dept.DeptID.ToString(), dept.DeptName));
            }

            #endregion

            if (string.IsNullOrEmpty(DeviceNO))//新增
            {
                ddlConnectType.SelectedIndex = 0;
            }
            else
            {
                #region 加载编辑的数据

                var info = DeviceInfoBLL.Selete(DeviceNO);
                txtDeviceNO.Text = info.DeviceNO;
                txtDeviceNO.ReadOnly = true;
                FindSelectItemInDDL(ddlDeviceType, info.DeviceTypeID.ToString());
                FindSelectItemInDDL(ddlDevicePlace, info.DevicePlaceID.ToString());
                FindSelectItemInDDL(ddlDept, info.DeviceDeptID.ToString());
                FindSelectItemInDDL(ddlConnectType, info.ConnectType.ToString());

                ipaIP.Value = info.IP;
                ipaSubMask.Value = info.SubnetMask;
                ipaDefaultGateway.Value = info.DefaultGateway;

                integerInput2.Text = info.Port.HasValue ? info.Port.Value.ToString() : null;

                txtDesc.Text = info.Desc;


                #endregion
            }
        }

        private void FindSelectItemInDDL(ComboBoxEx ddl, string value)
        {
            foreach (var item in ddl.Items)
            {
                var it = item as ComboBoxItem;
                if (it.Name == value)
                {
                    ddl.SelectedItem = item;
                    break;
                }
            }
        }

        private void ddlConnectType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (((sender as ComboBox).SelectedItem as ComboBoxItem).Name == "1")//TCP/IP
            {
                superTabItem1.Visible = true;
                superTabItem2.Visible = false;
            }
            else
            {
                superTabItem1.Visible = false;
                superTabItem2.Visible = true;
            }
            //superTabControl1.SelectedTab
        }

        private void btnTestConnect_Click(object sender, EventArgs e)
        {
            string ip = ipaIP.Text;

            RealTimeBoardAPI.OpenNet();

            StringBuilder ver = new StringBuilder();

            int returnCode = RealTimeBoardAPI.ReadVer(ver, new StringBuilder(ip), RealTimeBoardAPI.DefaultPort);

            RealTimeBoardAPI.CloseNet();

            if (returnCode == (int)ReturnCode.Success)
            {
                MyMessageBox.ShowMessage(this, "设备通讯成功！");
            }
            else
            {
                MyMessageBox.ShowMessage(this, "设备通讯失败！");
            }
        }


    }
}
